// pages/member/member.js
var goodsArr = require('../../utils/category')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    height:0,
    istab:false,
    tabCur: 0, //当前项
    rightCur: 0, // 用于实现左边联动右边
    goodsList: [],
    totalMoney: 0,
    totalCount: 0,
    show:false,
    cart:[],//已添加购物车
  },

  showPopup() {
    this.setData({ show: !this.data.show });
  },

  onClose() {
    this.setData({ show: false });
  },


  gl(e) {
    this.setData({
      tabCur: e.currentTarget.id,
      rightCur: e.currentTarget.id,
      istab: true
    })
  },
  scrollLink(e) {
    
    const scrollY = e.detail.deltaY;

    // if(scrollY < 0){
    //   if(this.getTabBar().data.showModalStatus){
    //     this.getTabBar().hideModal()
    //   }
    // } else {
    //   if(!this.getTabBar().data.showModalStatus){
    //     this.getTabBar().showModal()
    //   }
    // }
    let list = this.data.goodsList
    let itemHeight = 0;
    for (let i = 0; i < list.length; i++) {
      //拿到每个元素
      let els = wx.createSelectorQuery().select("#scroll-" + i);
      els.fields({
        size: true
      }, function (res) {
        list[i].top = itemHeight;
        itemHeight += res.height;
        list[i].bottom = itemHeight
      }).exec()
    }

    // 拿到滚动的高度
    let scrollTop = e.detail.scrollTop;
    let istab = this.data.istab
    for (let i = 0; i < list.length; i++) {
      let itemTop = list[i].top
      let itemBottom = list[i].bottom
      if (scrollTop > itemTop && scrollTop < itemBottom) {
        this.setData({
          tabCur: istab ? this.data.tabCur : i,
          istab:false
        })
        break
      }
    }
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(typeof this.getTabBar === 'function' && this.getTabBar()){
      this.getTabBar().setData({
          selected:1
        })
    }
  },

  onLoad:function(){
    // goodsArr.list.map(item => item.goods_list.map(good => good.selectCount = 0))
    this.setData({
      goodsList: goodsArr.list
    })
    var that = this;
    wx.getSystemInfo({
      success (res) {
        that.setData({
          height: res.screenHeight
        })
      }
    })
  },
  reduceGoods:function(e){
    const goodsListIndex = e.currentTarget.dataset['index']//类目位置
    const itemIndex = e.currentTarget.dataset['itemindex']//类目对应的item位置
    const itemId = e.currentTarget.dataset['itemid']//类目对应的item的id
    let tempList = this.data.goodsList
    let item = tempList[goodsListIndex].goods_list[itemIndex]
    if(item.selectCount > 0){
      item.selectCount = item.selectCount - 1
    }
    let currentCount = this.data.totalCount;
    let currentMoney = this.data.totalMoney;

    let tempCart = this.data.cart;
    const findIndex = tempCart.findIndex((item)=> item.id == itemId)
    if(findIndex > -1){
      tempCart.splice(findIndex,1)
    }

    this.setData({
      goodsList: tempList,
      totalCount: currentCount - 1,
      totalMoney: currentMoney - item.price,
      cart:tempCart
    })
  },

  calclulateCount:function(list){
    let tempList = [];
    list.forEach(goodlist=>{
      goodlist.goods_list.forEach(goodItem =>{
          if(goodItem.selectCount > 0){
            tempList.push(goodItem)
          }
        }
      )      
    })
    return tempList;
  },
  // 直接添加到购物车
  directAdd:function(e){
    const goodsListIndex = e.currentTarget.dataset['index']
    const itemIndex = e.currentTarget.dataset['itemindex']
    // const itemId = e.currentTarget.dataset['itemid']
    let addGood = {"count":1,"propertyValue":{"id":-1,"value":""}}
    this.asyncCart(addGood,goodsListIndex,itemIndex)
  },
  //跳转属性页面选择属性后添加到购物车
  toGoods:function(e){
    console.log("数据" + JSON.stringify(e))
    const goodsListIndex = e.currentTarget.dataset['index']
    const itemIndex = e.currentTarget.dataset['itemindex']
    const itemId = e.currentTarget.dataset['itemid']
    let that = this;
    wx.navigateTo({
      url: '/pages/addGoods/addGoods?id=' + itemId,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据-test使用
        acceptDataFromOpenedPage: function(data) {
          console.log("acceptDataFromOpenedPage接收跳转页面传入的参数" + data)
        },
        //接收被打开页面的事件调用 - test使用
        someEvent: function(data) {
          console.log("someEvent接收被打开页面的事件调用" + data)
        },
        addGoods:function(data){
          console.log("添加" + JSON.stringify(data))
          that.asyncCart(data,goodsListIndex,itemIndex)
        }
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })//test使用
      }
    })
  },

  asyncCart(addData,goodsListIndex,itemIndex){
    let tempList = this.data.goodsList
    let item = tempList[goodsListIndex].goods_list[itemIndex]
    if(addData.count > 0){
      item.selectCount = item.selectCount != null ? item.selectCount + addData.count : addData.count
    }

    const propertyId = addData.propertyValue.id;
    let cartTemp = this.data.cart;
  
    let tIndex = -1
    if(item.use_property == 1){
      tIndex = cartTemp.findIndex(tempItem => (tempItem.id == item.id) && (tempItem.propertyValue.id == propertyId))
    } else {
      tIndex = cartTemp.findIndex(tempItem => tempItem.id == item.id)
    }
    console.log(item.use_property + "位置" + tIndex)
    if(tIndex > -1) {
      cartTemp[tIndex].selectCount += addData.count;
    } else {
      cartTemp.push({
        "id":item.id,
        "goodsListIndex":goodsListIndex,
        "itemIndex":itemIndex,
        "name": item.name,
        "price":item.price,
        "selectCount" : 1,
        "propertyValue" : addData.propertyValue
      })
    }
    
    this.setData({
      totalCount: this.data.totalCount + addData.count,
      totalMoney: this.data.totalMoney + item.price * addData.count,
      goodsList: tempList,
      cart:cartTemp
    })
  },

  toPay:function(){
    let settlements = this.calclulateCount(this.data.goodsList)

    wx.navigateTo({
      url: '/pages/settlement/settlement?settlements=' + encodeURIComponent(JSON.stringify(settlements)),
      events: {//提供给其他页面通过emit调用的方法
        deleteGoods:function(item){

        },
        addGoods:function(item){

        },
        clearCar:function(data){

        }
      },
      success: function(res) {
        //跳转成功的回调
      }
    })
  },
  reduceCart(e){
    const clickIndex = e.currentTarget.dataset['index']//购物车中的位置
    const goodsListIndex = e.currentTarget.dataset['goodsindex']//类目位置
    const itemIndex = e.currentTarget.dataset['itemindex']//类目对应的item位置
    let tempCart = this.data.cart;
    let cartItem = tempCart[clickIndex]
    let tempDatas = this.data.goodsList;  
    let originItem = tempDatas[goodsListIndex].goods_list[itemIndex]
    if(originItem.id == cartItem.id){
      originItem.selectCount -= 1
      cartItem.selectCount -= 1
      if(cartItem.selectCount < 1){
        tempCart.splice(clickIndex,1)
      }
    }
    this.refreshTotal(tempCart)
    this.setData({
      cart: tempCart,
      goodsList: tempDatas
    })
  },
  addCart(e){
    const clickIndex = e.currentTarget.dataset['index']//购物车中的位置
    const goodsListIndex = e.currentTarget.dataset['goodsindex']//类目位置
    const itemIndex = e.currentTarget.dataset['itemindex']//类目对应的item位置
    let tempCart = this.data.cart;
    let cartItem = tempCart[clickIndex]
    let tempDatas = this.data.goodsList;  
    let originItem = tempDatas[goodsListIndex].goods_list[itemIndex]
    if(originItem.id == cartItem.id){
      originItem.selectCount += 1
      cartItem.selectCount += 1
    }
    this.refreshTotal(tempCart)
    this.setData({
      cart: tempCart,
      goodsList: tempDatas
    })
  },
  refreshTotal(tempCart){
    let cartCount = 0;
    let cartMoney = 0;
    if((typeof tempCart) != 'undefined'){     
      tempCart.forEach(good=>{
        cartCount += good.selectCount
        cartMoney += (good.selectCount * good.price)
      })
    }

    if(cartCount <= 0){
      this.setData({
        totalCount:cartCount,
        totalMoney:cartMoney,
        show: false
      })
    } else {
      this.setData({
        totalCount:cartCount,
        totalMoney:cartMoney,
      })
    }
  },
  son(){}
})
//总额和总数明日开发

